package com.situ.stmall.manger.controller.api;

import com.situ.stmall.manger.entity.Admin;
import com.situ.stmall.manger.entity.Result;
import com.situ.stmall.manger.service.AdminService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/admin")
@AllArgsConstructor
public class APIAdminController {
    private AdminService adminService;



    @PostMapping("/login")
    public Result login(Admin admin, String vercode , HttpSession session){
        //验证验证码

        String sVercode = (String) session.getAttribute("vercode");
        if(sVercode ==null ||sVercode.equals(vercode)){
            //session过期或验证码不等
            return Result.error("验证码错误");

        }
        try {
            admin = adminService.login(admin);//数据库中查询到的admi
            //登陆成功，信息保存到session
            admin.setPassword(null);
            admin.setSalt(null);
            session.setAttribute("admin",admin);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/logout")
    public Result logout(HttpSession session){
        //清除session
        session.invalidate();
        return Result.success();
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param reptPassword
     * @param session
     * @return
     */
    @PostMapping("/modifyPwd")//->修改
    public Result modifyPwd(String oldPassword,String newPassword,
                            String reptPassword,HttpSession session){
        //获取当前用户的session信息
        Admin admin = (Admin) session.getAttribute("admin");
        try {
            adminService.modifyPwd(admin.getId(),oldPassword,newPassword,reptPassword);
            //修改成功
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }

    @PutMapping//—>添加
    public Result edit(Admin admin,HttpSession session){
        //当前用户的id从session中取，不应该让用户出入id，可能输入别人的id
        Admin loginAdmin = (Admin) session.getAttribute("admin");
        admin.setId(loginAdmin.getId());
        try {
            adminService.edit(admin);
            //修改成功
            return  Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());

        }
    }

    @GetMapping("/getLogin")
    public Result getLogin(HttpSession session){
        //获取当前登陆用户
        Admin admin = (Admin) session.getAttribute("admin");

        if(admin!=null){
            //将当前用户信息取出来给客户端
            return Result.success(admin);
        }else{
            return Result.error("未登录！");
        }
    }

}
